package com.czk.utlls;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 临时素材上传
 *
 * @Author:ChenZhangKun
 * @Date: 2021/8/3 15:00
 */
@Component
public class UploadTempFile {
    @Value("${tempfile:}")
    private String tempFileUrl;
    @Autowired
    private TokenUtil tokenUtil;
    @Value("${getTempFileUrl}")
    private String getTokenUrl;

    public String upload(String path, String type) {
        File file = new File(path);
        tempFileUrl = tempFileUrl.replace("ACCESS_TOKEN", tokenUtil.getToken().getAccessToken()).replace("TYPE", type);
        try {
            URL url = new URL(tempFileUrl);
            // 强转为安全连接
            HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
            // 设置连接的信息
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            // 不适用缓存
            urlConnection.setUseCaches(false);
            // 长连接
            urlConnection.setRequestProperty("connection", "keep-alive");
            urlConnection.setRequestProperty("Charset", "utf-8");
            String boundary = System.currentTimeMillis() + "-----";
            // 数据的边界
            urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            // 准备数据
            // 第一部分，头部信息
            StringBuilder builder = new StringBuilder();
            builder.append("--");
            builder.append(boundary);
            builder.append("\r\n");
            builder.append("Content-Disposition:form-data;name=\"media\";filename=\" " + file.getName() + "\"\r\n");
            builder.append("Content-Type:application/octet-stream\r\n\r\n");
            // 获取输出流
            OutputStream outputStream = urlConnection.getOutputStream();
            outputStream.write(builder.toString().getBytes());
            // 第二部分，文件内容
            byte[] b = new byte[1024];
            int len = 0;
            InputStream inputStream = new FileInputStream(file);
            while ((len = inputStream.read(b)) != -1) {
                outputStream.write(b, 0, len);
            }
            // 第三部分， 尾部信息
            String foot = "\r\n--" + boundary + "--\r\n";
            outputStream.write(foot.getBytes());
            outputStream.flush();
            outputStream.close();
            // 读数据
            InputStream inputStream1 = urlConnection.getInputStream();
            StringBuilder resp = new StringBuilder();

            while ((len = inputStream1.read(b)) != -1) {
                resp.append(new String(b, 0, len));
            }
            return resp.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void getTempFile(String mediaId) {
        String accessToken = tokenUtil.getToken().getAccessToken();
        getTokenUrl = getTokenUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID ", mediaId);
        // 直接发get请求
    }

    /**
     * 上传永久图片
     *
     * @param path
     * @return
     */
    public String uploadForeverPic(String path,String type) {
        String foreverPath = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=TYPE";
        File file = new File(path);
        foreverPath = foreverPath.replace("ACCESS_TOKEN", tokenUtil.getToken().getAccessToken()).replace("TYPE",type);
        try {
            URL url = new URL(foreverPath);
            // 强转为安全连接
            HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
            // 设置连接的信息
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            // 不适用缓存
            urlConnection.setUseCaches(false);
            // 长连接
            urlConnection.setRequestProperty("connection", "keep-alive");
            urlConnection.setRequestProperty("Charset", "utf-8");
            String boundary = System.currentTimeMillis() + "-----";
            // 数据的边界
            urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            // 准备数据
            // 第一部分，头部信息
            StringBuilder builder = new StringBuilder();
            builder.append("--");
            builder.append(boundary);
            builder.append("\r\n");
            builder.append("Content-Disposition:form-data;name=\"media\";filename=\" " + file.getName() + "\"\r\n");
            builder.append("Content-Type:application/octet-stream\r\n\r\n");
            // 获取输出流
            OutputStream outputStream = urlConnection.getOutputStream();
            outputStream.write(builder.toString().getBytes());
            // 第二部分，文件内容
            byte[] b = new byte[1024];
            int len = 0;
            InputStream inputStream = new FileInputStream(file);
            while ((len = inputStream.read(b)) != -1) {
                outputStream.write(b, 0, len);
            }
            // 第三部分， 尾部信息
            String foot = "\r\n--" + boundary + "--\r\n";
            outputStream.write(foot.getBytes());
            outputStream.flush();
            outputStream.close();
            // 读数据
            InputStream inputStream1 = urlConnection.getInputStream();
            StringBuilder resp = new StringBuilder();

            while ((len = inputStream1.read(b)) != -1) {
                resp.append(new String(b, 0, len));
            }
            return resp.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
